import { HubConnectionBuilder, HubConnectionState } from "@microsoft/signalr"; // 导入 SignalR 库
import axios from "axios";
import { format } from "date-fns";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";

function Instore() {
  // 使用 useParams 钩子来获取动态参数
  const { port } = useParams<{ port: string }>();
  const [waferModel, setWaferModel] = useState<string>("");
  const [waferBatch, setWaferBatch] = useState<string>("");
  const [customerCode, setCustomerCode] = useState<string>("");
  const [internalBatch, setInternalBatch] = useState<string>("");
  const [id, setId] = useState("0");
  const [imgs, setImgs] = useState<string[]>([]);
  const [errorCodes, setErrorCodes] = useState<Record<string, string>>({
    srm1: "报警数据会显示红色",
    srm2: "默认数据",
    srm3: "无",
    srm4: "无",
    cv1: "无",
    cv2: "无",
    cv3: "无",
    cv4: "无",
    cv5: "无",
    cv6: "无",
    cv7: "无",
    cv8: "无",
    cv9: "无",
    cv10: "无",
    cv11: "无",
    cv12: "无",
    port1: "无",
    port2: "无",
    port3: "无",
    port4: "无",
    port5: "无",
    port6: "无",
  });
  // 状态：表格数据
  const [tableData, setTableData] = useState([
    {
      sequence: 1,
      aLot: "AAD1235.1",
      time: "2025/5/15 20:00",
      status: "[成功]",
      remake: "默认数据",
    },
  ]);

  // 更新错误代码的方法
  const updateErrorCode = (deviceCode: string, newErrorCode: string) => {
    setErrorCodes((prev) => ({
      ...prev,
      [deviceCode]: newErrorCode,
    }));
  };

  interface motreadData {
    id: string; // 主键
    locNo: string; // 站台号
    barcodeStatus: number; // 读码状态
    barcode1: string; // 条码1
    barcode1Old: string; // 条码1原值
    barcode2: string; // 条码2
    uniiCode: string; // UNII编码
    palletBarcode: string; // 托盘条码
    describe: string; // 描述
  }

  // 定义 堆垛机信息参数
  interface SrmInfo {
    srmCode: number; // 堆垛机编码
    errCode: string; // 错误代码
    runMode: string; // 运行模式
    x: number; // X坐标
    y: number; // Y坐标
    z: number; // Z坐标
    serialNo: number; // 流水号
    funcCode: number; // 功能码
    palletCode: number; // 托盘编码
    row: number; // 排
    col: number; // 列
    layer: number; // 层
    shelfNo: number; // 库台号
    hasGoods: boolean; // 是否有货物
  }

  // 定义 输送线信息参数
  interface CovInfo {
    deviceCode: string; // 设备编码
    errCode: string; // 错误代码
    runMode: string; // 出入模式
    hasGoods: boolean; // 上料口侧是否有货物   1巷道
    hasGoodsCache: boolean; // 缓存侧是否有货物  2巷道
    hasGoodsIn: boolean; // 入库口侧是否有货物
    hasGoodsMove: boolean; // 移载平台侧是否有货物  移载平台
    x: number; // X坐标
    z: number; // Z坐标
    status: string; // 设备状态
    onCode: string; // 上料口码
    midCode: string; // 缓存口码
    downCode: string; // 下料口码
  }

  // 初始化 SignalR 连接
  const getConnection = new HubConnectionBuilder()
    .withUrl("http://192.168.3.101:3254/api/qdsignalhub") // 替换为你的 GET 接口 SignalR Hub URL
    .build();

  useEffect(() => {
    // 启动连接并设置数据接收处理
    const startConnections = async () => {
      try {
        // 检查连接状态并在必要时停止连接
        if (getConnection.state !== HubConnectionState.Disconnected) {
          await getConnection.stop(); // 停止现有连接
        }

        // 启动 SignalR 连接
        await getConnection.start();
        console.log("GET SignalR connected.");

        getConnection.on("ZZCNR", (data) => {
          const readData: motreadData[] = data; // 解析并断言类型
          // 找到 readData 中 port 对应的 locNo 的数据
          const index = readData.findIndex((item) => item.locNo == port);
          console.log("ZZCNR", data);
          if (index === -1) {
            setWaferModel("");
            setWaferBatch("");
            setCustomerCode("");
            setInternalBatch("");
          } else {
            setWaferModel(readData[index].barcode1.split(";")[0]);
            setWaferBatch(readData[index].barcode1.split(";")[1]);
            setCustomerCode(readData[index].barcode1.split(";")[2]);
            setInternalBatch(readData[index].barcode1.split(";")[3]);
            setId(readData[index].id);
            //分裂出数据
                      const tableData: string[] = readData[index].barcode1Old.split("=");
                      // 处理表格数据
                      setTableData(
                        tableData.map((item, no) => {
                          const date = new Date(); // 获取当前日期时间
                          return {
                            sequence: no + 1,
                            aLot: item.split(";")[3],
                            time: format(date, "yyyy/MM/dd HH:mm"), // 使用date-fns的format方法格式化日期时间
                            status:
                              readData[index].barcodeStatus < 90
                                ? "[成功]"
                                : "[失败]",
                            remake: readData[index].describe,
                          };
                        })
                      );
                      if (readData[index].barcode1 == "") {
                        console.log("失败");
                        setTableData([]);
                      }
          }
        });

        // // 注册接收 Srm 数据的处理
        // getConnection.on("ReceiveSrmData", (data) => {
        //   const info: SrmInfo = JSON.parse(data);
        //   // 根据数据更新错误代码
        //   updateErrorCode(
        //     `srm${info.srmCode}`,
        //     info.errCode == null ? "无" : info.errCode
        //   );
        // });

        // // 注册接收 Cov 数据的处理
        // getConnection.on("ReceiveCovData", (data) => {
        //   const info: CovInfo = JSON.parse(data);
        //   // 根据数据更新错误代码
        //   updateErrorCode(
        //     info.deviceCode,
        //     info.errCode == null ? "无" : info.errCode
        //   );
        // });

        getConnection.on("WJM" + port, (data) => {
          console.log("WJM" + port, data);
          setImgs(data);
        });
      } catch (err) {
        console.error("Error while starting connections: ", err);
      }
    };

    startConnections();

    // 清理连接
    return () => {
      getConnection.stop(); // 停止 GET SignalR 连接
    };
  }, []);

  // 清除扫码接口
  const clearScanAPI = async (id: string) => {
    try {
      const response = await axios.post(
        "http://192.168.3.101:3254/api/motreadbarcode/cleanbarcode",
        {
          // 发送包含 id 的数据
          id,
        },
        {
          headers: {
            "Content-Type": "application/json",
            // 如果需要认证头，可以在这里添加
            // 'Authorization': 'Bearer your-token'
          },
        }
      );

      console.log("清空扫码结果成功:", response.data);
    } catch (error) {
      console.error("清空扫码结果时发生错误:", error);
    }
  };

  // 清除扫码结果的函数
  const clearScanResults = () => {
    try {
      // 调用清空扫码接口
      clearScanAPI(id);

      // 清空相关状态
      setWaferModel("");
      setWaferBatch("");
      setCustomerCode("");
      setInternalBatch("");
      setId("0");
    } catch (error) {
      console.error("清除扫码结果时发生错误:", error);
    }
  };

  return (
    <div
      className="app"
      style={{
        display: "flex",
        justifyContent: "space-between", // 使用 space-between 来确保左右部分撑满屏幕
        alignItems: "stretch", // 确保子元素的高度撑满父容器
        height: "100vh",
        width: "100vw",
        backgroundColor: "white",
        color: "black",
        border: "1px solid black", // 整个应用区域加上边框
      }}
    >
      {/* 左边部分 */}
      <div
        style={{
          flex: 7,
          display: "flex",
          flexDirection: "column", // 添加列方向排列
          border: "1px solid black", // 左边部分加上边框
          height: "100%", // 确保左边部分的高度撑满父容器
          position: "relative", // 添加相对定位
        }}
      >
        <div
          style={{
            fontSize: "32px", // 放大字体，可以根据需要调整字号
            justifyContent: "flex-start", // 将内容对齐到左边
            alignItems: "center",
            display: "flex",
            height: "50px", // 设置一个合适的高度以便“端口号”显示在顶部
          }}
        >
          <strong>端口号: {port}</strong>
        </div>
        <div
          style={{
            display: "flex",
            justifyContent: "center", // 将内容居中显示
            width: "100%", // 宽度由 flex 属性决定
          }}
        >
          <form
            style={{
              display: "flex",
              flexDirection: "column",
              width: "100%", // 设置表单的宽度为100%，撑满容器
              fontSize: "18px", // 增加字体大小
            }}
          >
            <div
              style={{
                display: "flex",
                alignItems: "center", // 垂直居中对齐
                marginLeft: "80px", // 设置间距
                marginRight: "80px", // 设置间距
                marginTop: "20px", // 设置顶部间距
                marginBottom: "20px", // 设置底部间距
                justifyContent: "space-between", // 水平两端对齐，使输入框靠右
              }}
            >
              <label
                htmlFor="waferModel"
                style={{
                  fontSize: "24px",
                  fontWeight: "bold",
                  marginRight: "10px",
                }}
              >
                晶圆型号:
              </label>
              <input
                type="text"
                id="waferModel"
                name="waferModel"
                value={waferModel}
                readOnly // 添加 readOnly 属性
                style={{
                  fontSize: "24px",
                  fontWeight: "bold",
                  flex: 1,
                  marginRight: "10px",
                  backgroundColor: "#f0f0f0",
                  color: "black", // 设置字体颜色为黑色
                }}
              />{" "}
              {/* 使用 flex: 1 使输入框撑满剩余空间 */}
              <label
                htmlFor="customerCode"
                style={{
                  fontSize: "24px",
                  fontWeight: "bold",
                  marginRight: "10px",
                }}
              >
                客户代码:
              </label>
              <input
                type="text"
                id="customerCode"
                name="customerCode"
                value={customerCode}
                readOnly // 添加 readOnly 属性
                style={{
                  fontSize: "24px",
                  fontWeight: "bold",
                  flex: 1,
                  backgroundColor: "#f0f0f0",
                  color: "black", // 设置字体颜色为黑色
                }}
              />
            </div>
            <div
              style={{
                display: "flex",
                alignItems: "center", // 垂直居中对齐
                marginLeft: "80px", // 设置间距
                marginRight: "80px", // 设置间距
                marginTop: "20px", // 设置顶部间距
                marginBottom: "20px", // 设置底部间距
                justifyContent: "space-between", // 水平两端对齐，使输入框靠右
              }}
            >
              <label
                htmlFor="waferBatch"
                style={{
                  fontSize: "24px",
                  fontWeight: "bold",
                  marginRight: "10px",
                }}
              >
                晶圆批次:
              </label>
              <input
                type="text"
                id="waferBatch"
                name="waferBatch"
                value={waferBatch}
                readOnly // 添加 readOnly 属性
                style={{
                  fontSize: "24px",
                  fontWeight: "bold",
                  flex: 1,
                  marginRight: "10px",
                  backgroundColor: "#f0f0f0",
                  color: "black", // 设置字体颜色为黑色
                }}
              />{" "}
              {/* 使用 flex: 1 使输入框撑满剩余空间 */}
              <label
                htmlFor="internalBatch"
                style={{
                  fontSize: "24px",
                  fontWeight: "bold",
                  marginRight: "10px",
                }}
              >
                内部批号:
              </label>
              <input
                type="text"
                id="internalBatch"
                name="internalBatch"
                value={internalBatch}
                readOnly // 添加 readOnly 属性
                style={{
                  fontSize: "24px",
                  fontWeight: "bold",
                  flex: 1,
                  backgroundColor: "#f0f0f0",
                  color: "black", // 设置字体颜色为黑色
                }}
              />
            </div>
          </form>
        </div>
        <div style={{ display: "flex", justifyContent: "center" }}>
          <button
            onClick={clearScanResults}
            style={{
              fontSize: "20px",
              padding: "10px 20px",
              backgroundColor: "blue",
              color: "white",
              border: "none",
              borderRadius: "5px",
            }}
          >
            清除扫码
          </button>
        </div>
        <div
          style={{
            display: "flex",
            justifyContent: "space-around",
            flexWrap: "wrap",
            width: "100%", // 设置一个固定宽度，确保子元素可以正确换行
          }}
        >
          {imgs.map((imageName, index) => (
            <img
              key={index}
              src={`/external-images/Port0${port}/${imageName}`} // 替换为实际图片路径和乱码文件名
              alt={`Placeholder ${index + 1}`}
              style={{
                width: "37%", // 设置为45%，留出一定的间距，也可以根据实际调整
                height: "auto",
                objectFit: "cover",
                borderRadius: "5px",
                border: "1px solid #555",
                boxShadow: "0 4px 8px rgba(0,0,0,0.3)",
                margin: "10px", // 添加间距，使图片之间有间隔
              }}
            />
          ))}
        </div>
      </div>

      {/* 右边部分 */}
      <div>
        <div
          style={{
            flex: 2,
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            border: "1px solid black", // 右边部分加上边框
            height: "30%", // 调整高度以适应新的布局
            width: "100%", // 宽度由 flex 属性决定
          }}
        >
          {/* 这里可以添加上部分的内容 */}
          {/* 表格 */}
      <table
        border={1}
        cellPadding="12.5"
        width="100%"
        style={{
          borderCollapse: "collapse",
          maxWidth: "100%",
          fontSize: "12px",
          backgroundColor: "white",
          color: "black",
        }}
      >
        <thead>
          <tr>
            <th>序列</th>
            <th>A LOT</th>
            <th>时间</th>
            <th>状态</th>
            <th>备注</th>
          </tr>
        </thead>
        <tbody>
          {tableData.map((row, index) => (
            <tr
              key={index}
              style={{
                backgroundColor:
                  row.status === "[失败]" ? "red" : "white",
              }}
            >
              <td>{row.sequence}</td>
              <td>{row.aLot}</td>
              <td>{row.time}</td>
              <td>{row.status}</td>
              <td>{row.remake}</td>
            </tr>
          ))}
        </tbody>
      </table>
        </div>
        <div
          style={{
            flex: 2,
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            border: "1px solid black", // 右边部分加上边框
            height: "70%", // 调整高度以适应新的布局
            width: "100%", // 宽度由 flex 属性决定
          }}
        >
          <table
            style={{
              width: "100%",
              borderCollapse: "collapse",
            }}
          >
            <thead>
              <tr>
                <th
                  style={{
                    padding: "10px",
                    border: "1px solid black",
                    textAlign: "center",
                    fontSize: "20px",
                    fontWeight: "bold",
                  }}
                >
                  设备编码
                </th>
                <th
                  style={{
                    padding: "10px",
                    border: "1px solid black",
                    textAlign: "center",
                    fontSize: "20px",
                    fontWeight: "bold",
                  }}
                >
                  错误代码
                </th>
              </tr>
            </thead>
            <tbody>
              {Object.entries(errorCodes).map(([key, value]) => {
                if (value !== "无") {
                  if (value === "默认数据") {
                    return (
                      <tr key={key}>
                        <td
                          style={{
                            padding: "10px",
                            border: "1px solid black",
                            textAlign: "center",
                            fontSize: "20px",
                            fontWeight: "bold",
                          }}
                        >
                          {key}
                        </td>
                        <td
                          style={{
                            padding: "10px",
                            border: "1px solid black",
                            textAlign: "center",
                            fontSize: "20px",
                            fontWeight: "bold",
                          }}
                        >
                          {value}
                        </td>
                      </tr>
                    );
                  } else {
                    return (
                      <tr key={key}>
                        <td
                          style={{
                            padding: "10px",
                            border: "1px solid black",
                            textAlign: "center",
                            fontSize: "20px",
                            fontWeight: "bold",
                            color: "red",
                          }}
                        >
                          {key}
                        </td>
                        <td
                          style={{
                            padding: "10px",
                            border: "1px solid black",
                            textAlign: "center",
                            fontSize: "20px",
                            fontWeight: "bold",
                            color: "red",
                          }}
                        >
                          {value}
                        </td>
                      </tr>
                    );
                  }
                }
                return null;
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

export default Instore;
